package gmed;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.io.*;
import java.sql.*;
import java.rmi.*;
import java.rmi.server.*;

public class medicamento_Impl extends UnicastRemoteObject implements medicamento {
	
	private String nome;
	private int idmedicamento;
	private static Connection conn = null;
	
	
	public medicamento_Impl(String nome) throws RemoteException{
		this.nome=nome;	
		
		if (conn == null)
			conn = DBConnection2.get_conn();
		java.sql.Statement st;
		try {
			st = conn.createStatement();
			java.sql.ResultSet rs = st
					.executeQuery("select nome, idmedicamento from medicamento where nome="
							+ nome);
			if (rs.first()) { 
				this.nome = rs.getNString(1);
				this.idmedicamento=rs.getInt(2);
				
			} else {
				if (st.execute("insert into medicamento (nome) values ("
						+ nome + ")", st.RETURN_GENERATED_KEYS)) {
					rs = st.getGeneratedKeys();
					rs.first();
					this.idmedicamento= rs.getInt(1);
				}
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
}
	
	public String get_nome() throws RemoteException {	
		return nome;
	}
	
	public void elimina_medicamento(String nome){
		antes_eliminar();
		Statement st;
		try{
			if(conn==null)
				conn= DBConnection2.get_conn();
			st=conn.createStatement();
			String query="delete from medicamento where nome='"+this.nome+"'";
			st.execute(query);
		}catch (SQLException e){
	}
	}
	private void antes_eliminar(){
		Statement  st;
		try{
			if(conn==null)
				conn=DBConnection2.get_conn();
			st=conn.createStatement();
			String query="delete from receitas where receitas.idmedicamento=(select idmedicamento from medicamento where nome='"+this.nome+"')";
			st.execute(query);
		}catch(SQLException e){
			
		}
	}
	
	public boolean set_nome(String nome) throws RemoteException {
		this.nome = nome;
	//	this.update_field("nome", nome);
		return true;
	}
	
	
/*	private void update_field(String field, Object Value) {
		Statement st;
		try {
			if (conn == null)
				conn = DBConnection.get_conn();
			st = conn.createStatement();
			String query = "update medicamento set " + field + "='"
					+ Value.toString() + "' where nome=" + this.nome;
			System.err.println(query);
			st.execute(query);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}*/

}
